define(function (require) {
var app = require('app');
require('rolesdetails');
app.controller( 'userRolesController',["$scope", "$http", "$location","$state","$rootScope","$cookieStore", "$timeout","promptCache", function( $scope, $http, $location , $state,$rootScope,$cookieStore,$timeout,promptCache){
	// 默认关闭弹窗
	$(".modal-backdrop").remove();
	// 储存ID
	// $scope.roleGroupId = [];
	// 详情
	$scope.detailsInfo = {};
	// 修改
	$scope.editInfo = {};
	
	// 储存角色组ID
	$scope.roleGroupId = []
	
	//details
	$scope.rolesdetailsnew = [];
	
	
	// 分页
	function dataRendering() {
		$scope.paginationConf = {
	        currentPage    : 1,
	        totalItems     : 10,
	        itemsPerPage   : 10,
	        pagesLength    : 15,
	        perPageOptions : [10, 20, 30, 40, 50],
	        onChange: function(){
	        	var self = this;
	        	var pagingData = {
	        		pageNumber  : self.currentPage,  
					pageSize 	: self.itemsPerPage,  
	        	}
	        	//console.log(pagingData.pageNumber);
        	if( (($scope.isRequestCurrentPage != self.currentPage) || ($scope.isRequestItemsPerPage != self.itemsPerPage)) && (new Date() - $scope.nowTime > 500) )
	        	{	
	        		$scope.nowTime = new Date();
					$http({
						url    : $scope.zsUrl+'digitalhome-boss/admin/roleGroups/getRoleGroupsList',
						method : 'POST',
						data   : {
							pageNumber  : self.currentPage,  
							pageSize 	: self.itemsPerPage,  
						}
					}).then(
						function success(res) {
							if( '0000' == res.data.result_code ) 
							{
								// 角色组列表页面表格
								$scope.tabVal = res.data.result;
								// 遍历所有角色ID
								angular.forEach(res.data.result, function(obj, i) {
									$scope.roleGroupId[i] = obj.roleGroupId;
                				});
								
								$cookieStore.put('rolesdate',$scope.tabVal);
								// 总共有多少条数据
								self.totalItems = res.data.length;	
							}
							else
							{
								$scope.isNoData = false;
								return false;
							}
							//console.log(res.data.message);
							//console.log(res.data.result);
						}, 
						function error(err) {
							$scope.isNoData = false;
							console.log(err);
						}
					);

					$scope.isRequestCurrentPage = self.currentPage;
					$scope.isRequestItemsPerPage = self.itemsPerPage;

				}
	        }
	    }
  	}
  	dataRendering();
	// 确定新增（新增一条角色组列表数据）
	$scope.add = function() {
		// 新增角色组名、描述（封装成JSON）
		var newlyAddedData = {
			roleGroupName : $scope.newlyAddedRoleGroupName,
			description   : $scope.newlyAddedDescription,
		}

		$http({
			url    : $scope.zsUrl+'digitalhome-boss/admin/roleGroups/add',
			method : 'POST',
			data   : newlyAddedData, /* 将JSON发送给服务器 */
 
		}).then(function success(res) {
			//console.log(res.data);
			// 清空表单
			
			// 重新加载页面
				if( '0000' == res.data.result_code ){
					promptCache.successPrompt(res.data.message);
					$state.go("user.roles",{},{reload:true});
					$("#add").modal("hide");
					$scope.newlyAddedRoleGroupName = '';
					$scope.newlyAddedDescription = '';
				}else{
					promptCache.errorPrompt(res.data.message);
				}
		},
		function error(err){
			console.log(err);
		});

	}

	// 详情（用于向用户展示从服务器获取的数据）
	$scope.details = function($event, $index) {
		
//		$cookieStore.put('roleGroupIdcookie',$rootScope.roleGroupId);
//		$rootScope.roleGroupId =  $scope.roleGroupId[$index];
		//console.log($scope.roleGroupId[$index]);
		
		$("#details").modal("show");
		$http({
			url    : $scope.zsUrl+'digitalhome-boss/admin/roleGroups/getRoleGroupsInfo/'+$scope.roleGroupId[$index]+'',
			method : 'GET',
		}).then(function success(res){
				// 向用户展示从服务器获取到的数据
				$scope.rolesdetails = {
					roleGroupId 		: res.data.result.roleGroupId,
					roleGroupName 	 	: res.data.result.roleGroupName,
					description 		: res.data.result.description,
					createDate 		 	: res.data.result.createDate,
					createUserId 	 	: res.data.result.createUserId,
					lastUpdatedDate 	: res.data.result.lastUpdatedDate,
					lastUpdatedUserId 	: res.data.result.lastUpdatedUserId
				}
				//console.log($scope.rolesdetails);
				//$cookieStore.put('rolesdetails',$scope.rolesdetails);
			},
			function error(err) 
			{
				console.log(err);
			}
		);
	}
	
	

	// 修改（调用接口与“详情”相同，用于向用户展示从服务器获取的数据）
	$scope.edit = function($event, $index) {
		$http({
			url    : $scope.zsUrl+'digitalhome-boss/admin/roleGroups/getRoleGroupsInfo/'+$scope.roleGroupId[$index]+'',
			method : 'POST',
		}).then(function success(res) {
				// 向用户展示从服务器获取到的数据
				$scope.rolesupdate  = {
					roleGroupId 	: res.data.result.roleGroupId,
					roleGroupName 	: res.data.result.roleGroupName, 
					description 	: res.data.result.description 
				}	
				//console.log($scope.rolesupdate.roleGroupName);
				$cookieStore.put('rolesupdate',$scope.rolesupdate);
				$state.go("user.rolesupdate",{},{reload:true});
			},
			function error() {

			}
		);
	}

	
	

	
	
	// roles-selected
	$scope.rolesselected = [];  
	
    var rolesupdateSelected = function(action,roleGroupId){  
        if(action == 'add' && $scope.rolesselected.indexOf(roleGroupId) == -1){  
            $scope.rolesselected.push(roleGroupId);  
        }
        if(action == 'remove' && $scope.rolesselected.indexOf(roleGroupId)!=-1){  
            var idx = $scope.rolesselected.indexOf(roleGroupId);  
            $scope.rolesselected.splice(idx,1);   
        }  
    }  
 
    $scope.rolesupdateSelection = function($event,roleGroupId,tabVal){  
        var checkbox = $event.target;  
        var action = (checkbox.checked?'add':'remove');  
        rolesupdateSelected(action,roleGroupId); 
        console.log($scope.rolesselected);  
    }  
   
    $scope.rolesisSelected = function(id,val){  
        return $scope.rolesselected.indexOf(id)>=0;        
    } 
    
    $scope.all = function(tabVal){
    	$scope.rolesselected = []; 
    	if($scope.master == true){
        	$scope.userscheck = true;
        	angular.forEach(tabVal, function (i, index) {
                $scope.rolesselected.push(i.roleGroupId); 
           })
        	console.log($scope.rolesselected);
        }else{
        	$scope.userscheck = false;
        	$scope.rolesselected =[];
        }
    }
    
    // 删除（保存当前点击对象的$index、this指向）
	var _this = '', _index = 0;
	$scope.deletes = function($event, $index) {
		// 当前对象（this指向不变）
		_this = angular.element($event.target);
		// 每一行的序列号
		_index = $index;
		
		if($scope.rolesselected == ""){
			promptCache.prompt("请选中你要删除的数据！");
		}else{
			$("#delete").modal('show');
		}
		 console.log($scope.rolesselected);
		 
	}

	// 确定删除（用于用户删除数据）
	$scope.confirmDel = function($event) {
		var rolesselecteddate = {
			roleGroupId : $scope.rolesselected,
		}
		
		$http({
			url: $scope.zsUrl+'digitalhome-boss/admin/roleGroups/deleteInfo',
			method: 'POST',
			data: JSON.stringify(rolesselecteddate), /* 给服务器发送需要删除的数据对应的ID */
		}).then(function success(res) {
				// result_code == '0000' 则删除，否则不删除
				//console.log(rolesselecteddate);
				$state.reload();
				if( '0000' == res.data.result_code )
				{
					_this.parents('tr').remove();
					promptCache.successPrompt(res.data.message);
				}
				else 
				{
					console.log(res.data);
				}
			},
			function error(err) {
				console.log(err);
			}
		);

	}
	
		//Online editing
//		$cookieStore.remove('rolesdate');
		$scope.tabVal = $cookieStore.get('rolesdate');
		var dummydata = $scope.tabVal;
		$scope.roles_focus = function($index){
			//console.log($scope.tabVal[$index]);
			var rolesdate = {
				roleGroupId   : $scope.tabVal[$index].roleGroupId,
				roleGroupName : $scope.tabVal[$index].roleGroupName,
				description   : $scope.tabVal[$index].description,
			}
			//console.log(dummydata[$index].description,dummydata[$index].roleGroupName);
			//console.log($scope.tabVal[$index].description,$scope.tabVal[$index].roleGroupName);
			function rolesupdate(){
				$http({
					url   	: $scope.zsUrl+'digitalhome-boss/admin/roleGroups/modify',
					method  : 'POST',
					data    : rolesdate, /* 将JSON发送给服务器 */
				}).then(function success(res){
					//console.log($scope.tabVal);
					//console.log($scope.tabVal[$index]);
					// 重新加载页面
					
					if( '0000' == res.data.result_code ){
						promptCache.successPrompt("修改角色组成功","user.roles");
						var dummydata = $scope.tabVal;
					}else{
						promptCache.errorPrompt("修改角色组失败 ");	
					}
				},function error(err){
					console.log(err);
				});	
			}
			$timeout(function () {
                rolesupdate();
            }, 1500);
		}	
}])
.directive('selectline', function () {
        return {
            restrict: 'A',
            link: function (scope, element, attrs) {
//                element.bind('mouseover',function(event){
//                        this.select();
//                });
//              element.bind('click',function(event){
//                  this.select();
//              });
//              element.bind('focus',function(event){
//                  this.select();
//              });
            }
        };
    });
    
})

